import pinia, { useUserStore } from '@/store';

// 获取当前页面和参数
export const getUrlWithArgs = () => {
	const tabbarList = [
		'pages/index/index',
		'pages/class/index',
		'pages/ranking/index',
		'pages/my/index',
	];
	const currentPage: any = getCurrentPages().pop();
	const url = currentPage?.route; // 当前页面路径
	const options = currentPage?.options; // 当前页面参数
	let urlWithArgs = `/${url}?`;
	Object.keys(options).forEach(key => {
		const value = options[key];
		urlWithArgs += `${key}=${value}&`;
	});
	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
	let type = 'redirectTo';
	if (tabbarList.includes(url)) {
		type = 'redirectTo';
	}
	return { type, url: urlWithArgs };
};

// 未注册跳转授权页,获取之前的页面，以防回调
export const toAuthPage = (options = {}, beforePage = getUrlWithArgs()) => {
	uni.setStorageSync('getCurrentPageUrlWithArgs', beforePage);
	const userStore = useUserStore(pinia);
	// 登录微信可能并未选择账户信息
	let url = `/pages-user/login/index?`;
	if (userStore.tokenInfo.token && !userStore.userInfo.student_id) {
		// 跳转管理账号进行选择
		url = `/pages-user/account/index?`;
	}
	if (userStore.tokenInfo.token && userStore.userInfo.student_id && !userStore.userInfo.class_id) {
		// 跳转管理账号进行选择
		url = `/pages-user/personal/index?`;
	}
	Object.keys(options).forEach(key => {
		const value = options[key];
		url += `${key}=${value}&`;
	});
	uni.navigateTo({ url });
};

